/*	BuildScienceVessel class definition.
 *
*/

#include "BuildScienceVessel.h"

void BuildScienceVessel::Enter()
{
	DEBUG_PRINT("BuildScienceVessel(%p) %s entering\n", this, GetName().c_str());

}

void BuildScienceVessel::Execute()
{
	DEBUG_PRINT("BuildScienceVessel(%p) %s executing\n", this, GetName().c_str());
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* starList;
	BWAPI::Unit* star = NULL;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		starList = (*base)->GetBuildingsByType(BWAPI::UnitTypes::Terran_Starport);
		if(starList)
		{
			for(std::list<BWAPI::Unit*>::iterator it = starList->begin(); it != starList->end(); it++)
			{
				if (!(*it)->isTraining() && !(*it)->isBeingConstructed())
					star = *it;
			}
			if (star) 
			{
				BB->SpendResources(BWAPI::UnitTypes::Terran_Science_Vessel);
				star->train(BWAPI::UnitTypes::Terran_Science_Vessel);
			}
		}
	}
	control->FinishWithSuccess();
}

void BuildScienceVessel::Exit()
{
	DEBUG_PRINT("BuildScienceVessel(%p) %s exiting\n", this, GetName().c_str());

}

bool BuildScienceVessel::CheckConditions()
{
	DEBUG_PRINT("BuildScienceVessel(%p) %s checking conditions\n", this, GetName().c_str());
	std::list<BWAPI::Unit*>* sciVessels = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Science_Vessel);
	if(sciVessels)
	{	
		if(sciVessels->size() < 2)
		{
			if(BB->isBuildUnit(BWAPI::UnitTypes::Terran_Science_Vessel) )
			{
				DEBUG_PRINT("BuildScienceVessel(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());		
				return true;
			}
		}
	}
	else
	{
		if(BB->isBuildUnit(BWAPI::UnitTypes::Terran_Science_Vessel) )
		{
			DEBUG_PRINT("BuildScienceVessel(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
			return true;
		}
	}
	
	return false;
}